package com.scqkxx.gamebox.activity.group;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.ProgressCallback;
import com.avos.avoscloud.RefreshCallback;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.scqkxx.gamebox.R;
import com.scqkxx.gamebox.activity.myself.MyselfInforActivity;
import com.scqkxx.gamebox.databinding.ActivityGroupEditBinding;
import com.scqkxx.gamebox.databinding.ActivityJoinGroupBinding;
import com.scqkxx.gamebox.utils.DialogUtils;
import com.scqkzqtz.base.base.BaseActivity;
import com.scqkzqtz.base.library.utils.ToastUtils;
import com.wildma.pictureselector.PictureSelector;
//import com.scqkzqtz.takepictrue.TakePictrueUiils;

import java.io.IOException;
import java.util.List;

public class GroupEditActivity extends BaseActivity<ActivityGroupEditBinding> {

    private AVObject avObject;//编辑对象
    private String photoUrl;

    @Override
    public int setLayoutId() {
        return R.layout.activity_group_edit;
    }

    @Override
    public void init() {
        binding.titleView.setOnTitleClickListener(mTitleType -> finish());

        String groupId = getIntent().getStringExtra("groupId");
        AVQuery<AVObject> query = AVQuery.getQuery("Group");
        query.whereEqualTo("objectId", Integer.parseInt(groupId));
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> avObjects, AVException e) {
                Log.i("Group", avObjects + "");
                if (e == null && avObjects != null && avObjects.size() > 0) {
                    for (int i = 0; i < avObjects.size(); i++) {
                        if (avObjects.get(i).getObjectId().equals(groupId)) {
                            avObject = avObjects.get(i);
                            binding.etGroupName.setText(avObject.getString("name"));
                            binding.etGroupRemark.setText(avObject.getString("desc"));
                            binding.cbSetDefault.setChecked(avObject.getInt("isPublic") == 0);
                            setImageUrl(avObject.getString("avatar"));
                        }
                    }
                }
            }
        });

        binding.ivGroupImg.setOnClickListener(view -> {
                    PictureSelector
                            .create(GroupEditActivity.this, PictureSelector.SELECT_REQUEST_CODE)
                            .selectPicture(false, 200, 200, 1, 1);
                }
//                new TakePictrueUiils()
//                .setClip(false)
//                .setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark))
//                .setOnSelectTakePictrueListener((bitmap, pictrueFlie) -> commitPhoto(pictrueFlie))
//                .start(GroupEditActivity.this)
        );

        binding.btEditGroup.setOnClickListener(view -> {
            if (avObject == null) return;
            String name = binding.etGroupName.getText().toString();
            String desc = binding.etGroupRemark.getText().toString();

            avObject.put("name", name);
            avObject.put("desc", desc);
            if (!TextUtils.isEmpty(photoUrl)) {
                avObject.put("avatar", photoUrl);
            }
            avObject.put("isPublic", binding.cbSetDefault.isChecked() ? 0 : 1);
            avObject.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                        finish();
                    }
                }
            });
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
            if (data != null) {
                String picturePath = data.getStringExtra(PictureSelector.PICTURE_PATH);
                commitPhoto(picturePath);
            }
        }
    }

    /**
     * 上传头像
     *
     * @param imagePath
     */
    private void commitPhoto(final String imagePath) {
        DialogUtils.showDialog(this);
        try {
            final AVFile file = AVFile.withAbsoluteLocalPath("LeanCloud.png", imagePath);
            file.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (null == e) {
                        final String url = file.getUrl();
                        GroupEditActivity.this.photoUrl = url;
                        setImageUrl(url);
                    } else {
                        ToastUtils.showShortToast(GroupEditActivity.this, "图片上传失败..");
                    }
                    DialogUtils.dismiss();
                }
            }, new ProgressCallback() {
                @Override
                public void done(Integer integer) {
                    // 上传进度数据，integer 介于 0 和 100。
                    Log.d("LeanCloud_imagePath", String.valueOf(integer));//返回一个唯一的 Url 地址
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置头像
     *
     * @param imageUrl
     */
    private void setImageUrl(String imageUrl) {
        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.icon_user_header_default)
                .error(R.mipmap.icon_user_header_default)
                .centerCrop()
                .circleCrop();
        Glide.with(this).load(imageUrl).apply(options).into(binding.ivGroupImg);
    }

}
